'use strict'

import axios from 'axios'
import router from '@/router'
import { Toast, Dialog, Notify } from 'vant'
// axios.defaults.baseURL = 'http://39.106.139.151:8585/xbkj-dj/' // 39
// axios.defaults.baseURL = '/xbkj-dj'

let loadingInstance
axios.interceptors.request.use(config => { // 这里的config包含每次请求的内容
  config.headers['content-type'] = 'application/json; charset=utf-8'
  config.headers['Access-Control-Allow-Origin'] = 'application/json; charset=utf-8'

  config.headers.dataType = 'json'
  // 判断localStorage中是否存在api_token
  if (localStorage.getItem('token')) {
    //  存在将api_token写入 request header
    config.headers.token = localStorage.getItem('token')
  }
  loadingInstance = Toast.loading({
    duration: 0,
    forbidClick: true,
    loadingType: 'spinner',
    message: '加载中...'
  })
  return config
}, err => {
  loadingInstance.clear()
  return Promise.reject(err)
})

axios.interceptors.response.use(
  response => {
    loadingInstance.clear()
    const data = response.data
    if (data.code == 0) {
      return data
    } else {
      if (data.code === 401) {
        Dialog.alert({
          message: '登录失效，请重新登录'
        }).then(() => {
          localStorage.removeItem('token')
          router.replace('/login')
        })
      } else {
        Notify({
          message: data.msg,
          duration: 1000,
          background: '#FF4444'
        })
      }
      return Promise.reject(data) // 返回接口返回的错误信息
    }
  },
  error => {
    loadingInstance.clear()
    if (error.response) {
      switch (error.response.status) {
        case 401:
          Dialog.alert({
            message: '登录失效，请重新登录'
          }).then(() => {
            localStorage.removeItem('token')
            router.replace('/login')
          })
      }
    }
    if (error.response) {
      return Promise.reject(error.response.data) // 返回接口返回的错误信息
    } else {
      Notify({
        message: error.message,
        duration: 1000,
        background: '#FF4444'
      })
    }
  }
)

// 请求方式的配置
export default {
  post (url, data) { // post
    return axios({
      method: 'post',
      url,
      data: JSON.stringify(data),
      timeout: 1000 * 10
    }).then(
      (response) => {
        return response
      }
    ).then(
      (res) => {
        return res
      }
    )
  },
  get (url, params) { // get
    return axios({
      method: 'get',
      url,
      params, // get 请求时带的参数
      timeout: 1000 * 10
    }).then(response => {
      return response
    }).then(res => {
      return res
    })
  }
}
